import csv
import sys
import os
from itertools import groupby
from tempfile import NamedTemporaryFile
from datetime import datetime, timedelta
import re

time_advance = 5

def process_admin(input_filepath, output_root = "."):
    """
    1. 处理CSV数据：
        1. 剔除非空数据
        2. 保留'手机号码'列之前的数据
        3. 排除'点单金额', '配送费', '优惠金额' 列
        4. 将所有标题中带有的'选择配送时间点'的内容统计为一列'选择配送时间点'
        5. 将所有标题中带有的'选择商家'且包含'【'和'】'符号的列合并为'选择商家'
        6. 将'选择配送时间点', '选择商家' 这两列放到 '选择下单类型' 列之后
        7. 1级规则为基于'选择配送时间点'排序，注意配送时间点是'HH:MM'24小时制格式，你需要转化并比较时间的早晚，然后从早到晚排序
        8. 2级规则为基于'选择商家'分类归纳排序
        9. 3级规则为基于'序号'从小到大排序
        10. 从'选择配送时间点开始'到'配送地点'之间的数据，对于每一条数据，收集非空数据用' | '拼接，统一收集到'订单详情'的新列中，然后去除被收集的列。
        11. 输出到'_admin.csv'文件

    Args:
        input_filepath (str): 输入CSV文件路径。
    """
    new_mode = True if "_新_" in os.path.basename(input_filepath) else False
    output_filepath = os.path.join(output_root, os.path.basename(input_filepath).rsplit('.')[0] + "_admin.csv")

    with NamedTemporaryFile(mode='w+', newline='', encoding='utf-8-sig', delete=False) as tmpfile:
        with open(input_filepath, 'r', encoding='utf-8-sig') as infile, \
                open(tmpfile.name, 'w', newline='', encoding='utf-8-sig') as outfile:
            reader = csv.reader(infile)
            writer = csv.writer(outfile)

            header = next(reader)  # 读取标题行
            phone_index = header.index('手机号码')  # 找到'手机号码'列的索引
            if not new_mode:
                location_index = header.index('配送地点')  # 找到'配送地点'列的索引
                exclude_columns = ['点单金额', '配送费', '优惠金额']  # 要排除的列名

                # 找到所有'选择配送时间点'列的索引
                time_columns = [i for i, col in enumerate(header) if '选择配送时间点' in col]

                # 找到所有包含'选择商家'且带有'【'和'】'符号的列的索引
                shop_columns = [i for i, col in enumerate(header) if '选择商家' in col and '【' in col and '】' in col]

                
                # 统计每一列非空单元格的数量, 并排除指定列，只统计到'end_index'列
                # 如果是新表单统计到"手机号码"列，旧表单统计到"配送地点"
                end_index = location_index if new_mode else phone_index
                non_empty_counts = [0] * (end_index + 1) 
                for row in reader:
                    for col_index, cell in enumerate(row[:end_index + 1]):
                        if header[col_index] in exclude_columns or col_index in time_columns or col_index in shop_columns:
                            continue
                        if cell.strip() != "":
                            non_empty_counts[col_index] += 1

                # 筛选非空列的标题和数据，排除指定列，只处理到'配送地点'列
                filtered_header = [header[i] for i in range(end_index + 1) if
                                non_empty_counts[i] > 0 and header[
                                    i] not in exclude_columns and i not in time_columns and i not in shop_columns]
                print("1",filtered_header)

                # 找到'选择下单类型'列的索引
                shop_type_index = filtered_header.index('选择下单类型')

                print("2",shop_type_index)
                

                # 将'选择配送时间点'和'选择商家'插入到'选择下单类型'列之后
                filtered_header.insert(shop_type_index + 1, '选择商家')
                filtered_header.insert(shop_type_index + 2, '选择配送时间点')

                print("3",filtered_header)
                print("4",filtered_header)

                # 添加'手机号码'列
                filtered_header.append('手机号码')

                writer.writerow(filtered_header)

                # 将文件指针重新定位到开头
                infile.seek(0)
                next(reader)
                
                data = []
                for row in reader:
                    # 筛选非空列的数据，排除指定列，只处理到'配送地点'列
                    filtered_row = [cell for i, cell in enumerate(row[:end_index + 1]) if
                                    non_empty_counts[i] > 0 and header[
                                        i] not in exclude_columns and i not in time_columns and i not in shop_columns]

                    # 获取所有'选择配送时间点'的值并去重
                    time_values = list(
                        set([row[i] for i in time_columns if row[i].strip() != ""]))
                    # 获取所有'选择商家'的值并去重
                    shop_values = list(
                        set([row[i] for i in shop_columns if row[i].strip() != ""]))

                    # 将'选择配送时间点'和'选择商家'插入到'选择下单类型'列之后
                    filtered_row.insert(shop_type_index + 1, ', '.join(shop_values))
                    filtered_row.insert(shop_type_index + 2, ', '.join(time_values))
                    
                    # 添加'手机号码'列的数据
                    filtered_row.append(row[phone_index])
                    
                    if filtered_row:
                        data.append(dict(zip(filtered_header, filtered_row)))
                else:
                    """
                    1. 选择配送时间点已经合并
                    2. 选择配送地点移动到表单开头
                    """
                    shop_columns = [i for i, col in enumerate(header) if '选择商家' in col and '【' in col and '】' in col]
                    exclude_columns = ['点单金额', '配送费', '优惠金额']  # 要排除的列名
                    end_index = phone_index
                    filtered_header = []
                    filtered_row = []
                    for i in range(end_index + 1):
                        filtered = True
                        for item in exclude_columns:
                            filtered = False if item in header[i] else filtered
                        if header[i] in time_columns or header[i] in shop_columns:
                            filtered = False
                        if filtered == True: 
                            filtered_header.append(header[i])
                            filtered_row.append(reader[i])
                    order_type_index = filtered_header.index('选择下单类型')
                    filtered_header.insert(order_type_index + 1, '选择商家')
                    filtered_header.insert(order_type_index + 2, '选择配送时间点')
                    writer.writerow(filtered_header)
                    # 将文件指针重新定位到开头
                    infile.seek(0)
                    next(reader)

                    data = []
                    for row in reader:
                        # 筛选非空列的数据，排除指定列

                        # 获取所有'选择配送时间点'的值并去重
                        time_values = list(
                            set([row[i] for i in time_columns if row[i].strip() != ""]))
                        # 获取所有'选择商家'的值并去重
                        shop_values = list(
                            set([row[i] for i in shop_columns if row[i].strip() != ""]))

                        # 将'选择配送时间点'和'选择商家'插入到'选择下单类型'列之后
                        filtered_row.insert(shop_type_index + 1, ', '.join(shop_values))
                        filtered_row.insert(shop_type_index + 2, ', '.join(time_values))
                        
                        # 添加'手机号码'列的数据
                        filtered_row.append(row[phone_index])
                        
                        if filtered_row:
                            data.append(dict(zip(filtered_header, filtered_row)))

        # 多级排序
        sorted_data = sorted(data, key=lambda row: (row['选择配送时间点'], row['选择商家'], int(row['序号'])))

        print("5", sorted_data)

        # 处理订单详情和活动情况
        for row in sorted_data:
            # 处理金额逻辑
            if row["选择下单类型"] == "活动下单":
                row["应付金额"] = float(row["应付金额"]) + 1.5
            # if row["选择商家"] == "红姐牛肉饭":
            #     price = float(row['应付金额']) - 1 if shop == "红姐牛肉饭" else float(row['应付金额']) - 1.5
            # 处理订单详情
            order_details = " | ".join([value for key, value in row.items()
                                        if key not in ['序号', '应付金额', '选择下单类型', '选择商家', '选择配送时间点', '手机号码', '配送地点', '活动码'] and value])
            row['订单详情'] = order_details

        # 移除不需要的列
        for row in sorted_data:
            for key in list(row.keys()):
                if key not in ['序号', '应付金额', '选择下单类型', '选择商家', '选择配送时间点', '订单详情', '手机号码', '配送地点']:
                    del row[key]

        with open(output_filepath, 'w', newline='', encoding='utf-8-sig') as outfile:
            writer = csv.DictWriter(outfile, fieldnames=sorted_data[0].keys())
            writer.writeheader()
            writer.writerows(sorted_data)

    os.remove(tmpfile.name)
    return output_filepath
    
def process_shop_order(input_filepath, output_root = "."):
    """
    1. 读取经过process_shop输出的csv文件
    2. 按照顺序，把具有相同'选择配送时间点'，聚合生成不同商家可读的订单制作数据，每个时间点生成一个格式为'（选择配送时间点数据）.txt'的文本

    Args:
        input_filepath (str): 输入CSV文件路径。
    """
    shop_dir = os.path.join(output_root, "shop_orders")
    os.makedirs(shop_dir, exist_ok=True)

    with open(input_filepath, 'r', encoding='utf-8-sig') as infile:
        reader = csv.DictReader(infile)
        data = sorted(reader, key=lambda row: row['选择配送时间点'])

        for time, group in groupby(data, key=lambda row: row['选择配送时间点']):
            time_obj = datetime.strptime(time, "%H:%M")
            time_obj -= timedelta(minutes=time_advance)
            new_time_str = time_obj.strftime("%H:%M")
            time_name = time.replace(":", "")
            with open(os.path.join(shop_dir, f"{time_name}_shop.txt"), 'w', encoding='utf-8-sig') as outfile:
                outfile.write(f"------\n{time}\n------\n\n")
                for shop, shop_group in groupby(group, key=lambda row: row['选择商家']):
                    outfile.write(f"-----\n{shop}\n-----\n")
                    for row in shop_group:
                        temp = row['订单详情'].replace(' | ', '\n').replace('，', '\n')
                        temp = re.sub(r'（\d+(.\d+)?）：\d+', '', temp).strip()
                        price = float(row['应付金额']) - 1 if shop == "红姐牛肉饭" else float(row['应付金额']) - 1.5
                        outfile.write(f"流水号：{row['序号']}\n总价：{price} 元\n订单详情：{temp}\n取餐时间：{new_time_str}\n\n")
                    outfile.write(f"\n==================\n\n")

def process_admin_order(input_filepath, output_root = "."):
    """
    1. 读取经过process_admin输出的csv文件
    2. 按照顺序，把具有相同'选择配送时间点'，聚合生成不同商家可读的订单制作数据，每个时间点生成一个格式为'（选择配送时间点数据）_admin.txt'的文本
    2. 需要额外显示手机号和手机尾号

    Args:
        input_filepath (str): 输入CSV文件路径。
    """
    admin_dir = os.path.join(output_root, "admin_orders")
    os.makedirs(admin_dir, exist_ok=True)

    with open(input_filepath, 'r', encoding='utf-8-sig') as infile:
        reader = csv.DictReader(infile)
        data = sorted(reader, key=lambda row: row['选择配送时间点'])

        for time, group in groupby(data, key=lambda row: row['选择配送时间点']):
            time_obj = datetime.strptime(time, "%H:%M")
            time_obj -= timedelta(minutes=time_advance)
            new_time_str = time_obj.strftime("%H:%M")
            time_name = time.replace(":", "")
            with open(os.path.join(admin_dir, f"{time_name}_admin.txt"), 'w', encoding='utf-8-sig') as outfile:
                outfile.write(f"------\n{time}\n------\n\n")

                for shop, shop_group in groupby(group, key=lambda row: row['选择商家']):
                    outfile.write(f"---\n{shop}\n---\n")
                    for row in shop_group:
                        temp = row['订单详情'].replace(' | ', '\n').replace('，', '\n')
                        # temp = re.sub(r'（\d+）：\d+', '', temp).strip()
                        temp = re.sub(r'（\d+(.\d+)?）：\d+', '', temp).strip()
                        temp2 = row['手机号码'][-4:]
                        price = float(row['应付金额']) - 1 if shop == "红姐牛肉饭" else float(row['应付金额']) - 1.5
                        outfile.write(f"流水号：{row['序号']}\n总价：{price} 元\n手机号：{row['手机号码']}\n手机尾号：{temp2}\n配送地点：{row['配送地点']}\n订单详情：{temp}\n取餐时间：{new_time_str}\n\n")
                    outfile.write(f"\n---\n\n")

def process_rider_order(input_filepath, output_root = "."):
    """
    1. 读取经过process_admin输出的csv文件
    2. 按照顺序，把具有相同'选择配送时间点'，聚合生成不同商家可读的订单制作数据，每个时间点生成一个格式为'（选择配送时间点数据）_rider.txt'的文本
    3. 不显示手机号，但是要显示手机尾号

    Args:
        input_filepath (str): 输入CSV文件路径。
    """
    rider_dir = os.path.join(output_root, "rider_orders")
    os.makedirs(rider_dir, exist_ok=True)

    with open(input_filepath, 'r', encoding='utf-8-sig') as infile:
        reader = csv.DictReader(infile)
        data = sorted(reader, key=lambda row: row['选择配送时间点'])

        for time, group in groupby(data, key=lambda row: row['选择配送时间点']):
            time_obj = datetime.strptime(time, "%H:%M")
            time_obj -= timedelta(minutes=time_advance)
            new_time_str = time_obj.strftime("%H:%M")
            time_name = time.replace(":", "")
            with open(os.path.join(rider_dir, f"{time_name}_rider.txt"), 'w', encoding='utf-8-sig') as outfile:
                outfile.write(f"------\n{time}\n------\n\n")

                for shop, shop_group in groupby(group, key=lambda row: row['选择商家']):
                    outfile.write(f"---\n{shop}\n---\n")
                    for row in shop_group:
                        temp = row['订单详情'].replace(' | ', '\n').replace('，', '\n')
                        temp = re.sub(r'（\d+）：\d+', '', temp).strip()
                        temp = re.sub(r'（\d+(.\d+)?）：\d+', '', temp).strip()
                        temp2 = row['手机号码'][-4:]
                        outfile.write(f"流水号：{row['序号']}\n手机尾号：{temp2}\n配送地点：{row['配送地点']}\n订单详情：{temp}\n取餐时间：{new_time_str}\n\n")
                    outfile.write(f"\n---\n\n")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python script.py <input_filepath>")
        sys.exit(1)

    input_filepath = sys.argv[1]
    admin_file = process_admin(input_filepath)
    process_shop_order(admin_file)
    process_admin_order(admin_file)
    process_rider_order(admin_file)
